import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create({
  baseURL: 'https://likede2-admin.itheima.net/likede/',
  timeout: 5000
})

request.interceptors.request.use(
  (config) => {
    const { token } = store.state.user
    if (token) config.headers.Authorization = token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    response.data.success === false && Message.error('登录失败，填写错误')
    return response.data
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      Message.error('登录超时，请重新登录')
      store.commit('user/removeToken')
      router.push('/login')
    } else {
      Message.error(error.response.data)
    }
    if (error.message === 'Request failed with status code 500') {
      Message.error(error.response.data)
    }
    return Promise.reject(error)
  }
)
export default request
